//
//  WTBroadCastView.m
//  WTLiveSDKDemo
//
//  Created by ben on 2016/11/16.
//  Copyright © 2016年 ben. All rights reserved.
//

#import "WTBroadCastView.h"
#import "WTLiveRoomInfoService.h"
#import "WTLiveSDK.h"
#import "WTCategories.h"
#import "WTFocusService.h"
#import "WTLiveFinishView.h"
#import <IJKMediaFramework/IJKMediaFramework.h>


@implementation NSDictionary (WTBroadCast)
@dynamic anchor_id,verify_id,screening_id;
+ (NSDictionary*)wt_broadCast:(NSString *)anchor_id screening_id:(NSString *)screening_id verify_id:(NSString *)verify_id{
    return @{@"anchor_id":@([anchor_id longLongValue]),@"screening_id":@([screening_id integerValue]),@"verify_id":@([verify_id integerValue])};
}

- (NSString *)anchor_id{
    return self[@"anchor_id"];
}

- (NSString *)screening_id{
    return self[@"screening_id"];
}

- (NSString *)verify_id{
    return self[@"verify_id"];
}

@end


@interface WTBroadCastView ()<WTVideoViewDelegate>

@property (nonatomic,strong) WTLiveRoomInfoService* liveRoomInfoService;
@property (nonatomic,strong) WTFocusService*        focusService;
@property (nonatomic,strong) UIImageView*           placeHolderImageView;
@property (nonatomic,strong) id<IJKMediaPlayback> player;
@property (nonatomic,strong) WTLiveRoomInfoModel*   liveRoomInfoModel;
@property (nonatomic,strong) WTLiveFinishView*     liveFinishedView;
@end

@implementation WTBroadCastView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor blackColor];
        [self setup];
    }
    return self;
}


#pragma mark setup
- (void)setup{
    
    self.videoView = ({
        WTVideoView* view = [[WTVideoView alloc] init];
        view.delegate = self;
        view.playToolView.isLivePage = NO;
        [self addSubview:view];
        view;
    });
    
    self.placeHolderImageView = ({
        UIImageView*    imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage wt_imageWithName:@"wt_live_background_image"];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        [self addSubview:imageView];
        imageView;
    });
    
    self.liveFinishedView = ({
        
        WTLiveFinishView* view = nil;
        view = [[[NSBundle mainBundle] loadNibNamed:@"WTLiveFinishView" owner:self options:nil] lastObject];
        view.alpha = 0;
        [self addSubview:view];
        view;
    });
    
    
    [self layout];
}


#pragma mark layout
- (void)layout{
    
    [self.videoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
    }];
    
    [self.placeHolderImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
    }];
    
    
    [self.liveFinishedView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
    }];

    [self setNotify];
}

#pragma mark notifications
- (void)setNotify{
    
    __weak __typeof(self)weakSelf = self;
    [self addListenerForNotificationName:UIApplicationDidEnterBackgroundNotification handler:^(NSString *notificationName, NSDictionary *userInfo) {
        
        [weakSelf showGifLoding];
        [weakSelf.player pause];
        
    }];
    
    [self addListenerForNotificationName:UIApplicationWillEnterForegroundNotification handler:^(NSString *notificationName, NSDictionary *userInfo) {
        
        [weakSelf hideGifLoding];
        [weakSelf.player play];
        
    }];
    
    
    [self addListenerForNotificationName:IJKMPMoviePlayerLoadStateDidChangeNotification handler:^(NSString *notificationName, NSDictionary *userInfo) {
        [weakSelf stateDidChange];
    }];
    
    [self addListenerForNotificationName:IJKMPMoviePlayerPlaybackDidFinishNotification handler:^(NSString *notificationName, NSDictionary *userInfo) {
        [weakSelf didFinish];
    }];
    
    self.liveFinishedView.finishedViewBlock = ^(NSInteger type){
        if(type == 0){
            [weakSelf videoView:weakSelf.videoView focusUser_id:[NSString stringWithFormat:@"%@",[weakSelf.params anchor_id]] isFocus:!weakSelf.liveFinishedView.is_focoused];
        }else {
            if(weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(broadCastViewGoBack:)]){
                [weakSelf.delegate broadCastViewGoBack:weakSelf];
            }
        }
    };

}


#pragma mark getter
- (WTLiveRoomInfoService *)liveRoomInfoService{
    if(!_liveRoomInfoService){
        _liveRoomInfoService = [[WTLiveRoomInfoService alloc] init];
    }
    return _liveRoomInfoService;
}

- (WTFocusService *)focusService{
    if(!_focusService){
        _focusService = [[WTFocusService alloc] init];
    }
    return _focusService;
}

#pragma mark  WTVideoViewDelegate
- (void)videoView:(WTVideoView *)view focusUser_id:(NSString *)focusUser_id isFocus:(BOOL)isFocus{

    NSInteger focus = 0;
    if(isFocus){
        focus = 1;
    }
    __weak __typeof(self)weakSelf = self;
    [self.focusService start:@{@"session_token":WTConfig.session_token,@"anchor_id":@([focusUser_id longLongValue]),@"is_focus":@[@(focus),@1]} completionHandler:^(id responseObject, NSError *error) {

        if(!error){
            
            NSArray* focuss = responseObject;
            NSInteger f_status = [focuss[0] integerValue];
            NSInteger f_sucess = [focuss[1] integerValue];
            if(f_sucess == 1){ //操作成功
                [view updateFocusStatus:f_status];
                weakSelf.liveFinishedView.is_focoused = f_status;
                if(f_status == 1){ //关注
                    [weakSelf showTip:@"关注成功"];
                }else { //取消关注
                    [weakSelf showTip:@"取消关注成功"];
                }
            }
        }
    }];
}

- (void)videoViewOwnerEnter:(WTVideoView *)view{
    
    [self hideGifLoding];
    [self.player play];
}

- (void)videoViewOwnerLeave:(WTVideoView *)view{
    [self showGifLoding];
    [self.player pause];
}

- (void)videoViewOwnerFinishedLive:(WTVideoView *)view{
    //主播主动关闭直播 直播结束
    [self showFinishedView];
}

- (void)videoViewGiftDetail:(WTVideoView *)view{
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(broadCastViewGoGiftDetail:)]){
        [self.delegate broadCastViewGoGiftDetail:self];
    }
}

#pragma mark public
- (void)start{
    
    __weak __typeof(self)weakSelf = self;
    [self.liveRoomInfoService start:@{@"session_token":WTConfig.session_token,@"anchor_id":self.params[@"anchor_id"],@"screening_id":self.params[@"screening_id"]} completionHandler:^(id responseObject, NSError *error) {
        
        if(!error){
            
            WTLiveRoomInfoModel* model = responseObject;
            if(model.status_code == 6){
                [weakSelf begin:model];
            }else if(model.status_code == 3){ //需要付费
                if(weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(broadCastViewNeedPay:vertify_id:)]){
                    [weakSelf.delegate broadCastViewNeedPay:weakSelf vertify_id:weakSelf.params[@"verify_id"]];
                }
            }else if(model.status_code == 2){ //直播结束
                [weakSelf showFinishedView];
            }
            weakSelf.liveRoomInfoModel = model;
        }
    }];
}

- (void)begin:(WTLiveRoomInfoModel*)model{
    
    //赋值房间ID
    self.videoView.roomId = [model.roomAnchorModel.anchor_room_id integerValue];
    
    //设置房间的ID
    [[WTLiveSDK shareSDK].chatRoomManager setRoomID:[NSString stringWithFormat:@"%zd",[model.roomAnchorModel.anchor_room_id integerValue]]];
    
    //给房间添加主播信息
    self.videoView.liveExtendView.personInfoView.avatar = model.roomAnchorModel.anchor_avatar;
    self.videoView.liveExtendView.personInfoView.nick = model.roomAnchorModel.anchor_name;
    
    self.videoView.liveExtendView.coinView.coinCount = [NSString stringWithFormat:@"%lld",[model.roomAnchorModel.anchor_income longLongValue]];
    self.videoView.liveExtendView.accountView.cuteCode = [NSString stringWithFormat:@"%lld",[model.roomAnchorModel.anchor_cutecode longLongValue]];
    self.videoView.liveExtendView.personInfoView.isAttentioned = model.is_follow;
    
    //创建私信信息
    WTPrivateMessageAnchorModel* privateMessageAnchorModel = [[WTPrivateMessageAnchorModel alloc] init];
    privateMessageAnchorModel.anchor_name = model.roomAnchorModel.anchor_name;
    privateMessageAnchorModel.anchor_avatar = model.roomAnchorModel.anchor_avatar;
    privateMessageAnchorModel.anchor_level = model.roomAnchorModel.anchor_level;
    privateMessageAnchorModel.anchor_net_ease = model.roomAnchorModel.anchor_net_ease;
    privateMessageAnchorModel.anchor_user_id = [NSString stringWithFormat:@"%@",self.params[@"anchor_id"]];
    
    self.videoView.privateMessageView.anchor_info_model = privateMessageAnchorModel;
    self.videoView.privateMessageView.is_live  = NO;
    [self.videoView.privateMessageView update];
    
    //显示直播封面
    [self setPlayViewBackground:model.roomAnchorModel.anchor_avatar];
    
    //显示加载页面
    [self showGifLoding];
    
    //初始化视频播放器
    [self play:model.roomRoomModel.room_pull_url];
    
    //进入房间
    [[WTLiveSDK shareSDK].chatRoomManager enterChatroom:^(BOOL isEnter, NSInteger status) {
        if(isEnter){
            
            if(status == 1){ //房间进入成功
                
            }else {
                
            }
        }
    }];
}

- (void)showFinishedView{
    
    self.liveFinishedView.alpha = 1;
    [self.liveFinishedView update:[NSString stringWithFormat:@"%lld",[self.liveRoomInfoModel.roomAnchorModel.anchor_room_id longLongValue]]];
    [self.liveFinishedView update:self.liveRoomInfoModel.roomAnchorModel.anchor_avatar name:self.liveRoomInfoModel.roomAnchorModel.anchor_name];
    self.videoView.alpha = 0;
    [self.player view].alpha = 0;
    self.liveFinishedView.is_focoused = self.liveRoomInfoModel.is_follow;
}

- (void)finish{
    [self stop];
}

#pragma mark -private methods
- (void)setPlayViewBackground:(NSString*)avatar{
    
    NSString* placeHolderURL = avatar;

    if(placeHolderURL && placeHolderURL.length > 0){
        
        UIImage* image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:placeHolderURL];
        if(!image){
            [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:placeHolderURL] options:0 progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if(image){
                        self.placeHolderImageView.image = [image blurredImageWithRadius:50 iterations:2 tintColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:1]];
                    }
                });
            }];
        }else {
            self.placeHolderImageView.image = [image blurredImageWithRadius:50 iterations:2 tintColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:1]];
        }
    }else {
        self.placeHolderImageView.image = [UIImage wt_imageWithName:@"wt_live_background_image"];
    }
}

- (void)play:(NSString*)url{
    
    [self stop];
    
    IJKFFOptions *options = [IJKFFOptions optionsByDefault];
    [options setPlayerOptionIntValue:1  forKey:@"videotoolbox"];
    [options setPlayerOptionIntValue:29.97 forKey:@"r"];
    [options setPlayerOptionIntValue:512 forKey:@"vol"];
    
    
    self.player = [[IJKFFMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:url] withOptions:options];
    self.player.shouldAutoplay = NO;
    UIView* playerView = [self.player view];
    
    [self addSubview:playerView];
    [self bringSubviewToFront:self.videoView];
    
    [playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
    }];
    [self.player prepareToPlay];
}

- (void)stop{
    
    if(self.player){
        [self.player shutdown];
        [[self.player view] removeFromSuperview];
        self.player = nil;
    }
}


- (void)hidePlaceHolderView:(void (^)())success{
    
    if(self.placeHolderImageView.alpha == 0){
        return;
    }
    [UIView animateWithDuration:.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.placeHolderImageView.alpha = 0;
    } completion:^(BOOL finished) {
        success();
    }];
}

- (void)stateDidChange {
    
    if ((self.player.loadState & IJKMPMovieLoadStatePlaythroughOK) != 0) {
        if (!self.player.isPlaying) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hideGifLoding];
                [self hidePlaceHolderView:^{
                    [self.player play];
                }];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hideGifLoding];
            });
        }
    }else if (self.player.loadState & IJKMPMovieLoadStateStalled){ // 网速不佳, 自动暂停状态
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showGifLoding];
            [self.player pause];
        });
    }else if(self.player.loadState & IJKMPMovieLoadStatePlayable){
        
        
    }
}

- (void)didFinish{
    
    __weak __typeof(self)weakSelf = self;
    [self.liveRoomInfoService start:@{@"session_token":WTConfig.session_token,@"anchor_id":self.params[@"anchor_id"],@"screening_id":self.params[@"screening_id"]} completionHandler:^(id responseObject, NSError *error) {
        
        if(!error){
            
            WTLiveRoomInfoModel* model = responseObject;
            if(model.status_code == 6){
                [weakSelf play:model.roomRoomModel.room_pull_url];
            }else if(model.status_code == 3){ //需要付费
                
            }else if(model.status_code == 2){ //直播结束
                [weakSelf showFinishedView];
            }
        }
    }];
}

@end
